
let allAdmins = []
let filteredAdmins = []
let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let totalCount = 0; // 添加总数变量
let currentEditingAdminId = null;



// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initPage();
});

// 初始化页面
function initPage() {
    getAdmins();
    bindEvents();
}

function bindEvents() {
    document.getElementById('searchInput').addEventListener('input', debounce(filterAdmins, 300));

    document.getElementById('addAdminForm').addEventListener('submit', addAdmin);
    document.getElementById('editAdminForm').addEventListener('submit', handleEditAdmin);

    document.getElementById('confirmDeleteBtn').addEventListener('click', handleDeleteAdmin);

    document.getElementById('addAdminModal').addEventListener('hidden.bs.modal', resetAddForm);
    document.getElementById('editAdminModal').addEventListener('hidden.bs.modal', resetEditForm);
}


// 加载管理员数据
async function getAdmins() {
    showLoading();

    try {
        // 构建查询参数
        const params = new URLSearchParams({
            page: currentPage,
            page_size: pageSize
        });

        // 添加搜索条件
        const searchTerm = document.getElementById('searchInput').value.trim();
        if (searchTerm) {
            params.append('search', searchTerm);
        }

        const response = await fetch(`/api/admins?${params}`);
        const res = await response.json();

        if (res.success) {
            // 成功获取数据
            const data = res.data;
            allAdmins = data.items;
            filteredAdmins = [...allAdmins];

            // 更新分页信息
            totalPages = data.pagination.total_pages;
            currentPage = data.pagination.current_page;
            totalCount = data.pagination.total_count;

            displayAdmins();
        } else {
            console.error('加载管理员数据失败:', res.msg, res.error);
            showError('加载失败：' + res.msg + (res.error ? ' - ' + res.error : ''));
            showEmptyState();
        }
    } catch (error) {
        console.error('加载管理员数据出错:', error);
        showError('加载失败：网络错误');
        displayAdmins();
    }
}



// 显示管理员列表
function displayAdmins() {
    document.getElementById('loadingSpinner').style.display = 'none';

    if (filteredAdmins.length === 0) {
        showEmptyState();
        return;
    }

    document.getElementById('adminTableContainer').style.display = 'block';
    document.getElementById('emptyState').style.display = 'none';

    // 直接渲染当前页数据（已经是分页后的数据）
    renderAdminsTable(filteredAdmins);
    renderPagination();
    updateAdminCount(totalCount); // 显示总数而不是当前页数量
}

// 渲染管理员表格
function renderAdminsTable(admins) {
    const tbody = document.getElementById('adminTableBody');
    tbody.innerHTML = '';
    
    admins.forEach(admin => {
        const row = document.createElement('tr');
        row.className = 'fade-in';
        row.innerHTML = `
            <td>${admin.id}</td>
            <td><strong>${admin.username}</strong></td>
            <td><strong>${admin.role == '2' ? '超级管理员' : '普通管理员'}</strong></td>
            <td>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-primary btn-sm"
                            onclick="editAdmin(${admin.id})" title="编辑">
                        <i class="fas fa-edit"></i>
                        编辑
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm"
                            onclick="deleteAdmin(${admin.id}, '${admin.username}')" title="删除">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 渲染分页
function renderPagination() {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    // 上一页按钮
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">
            <i class="fas fa-chevron-left"></i>
            上一页
        </a>
    `;
    pagination.appendChild(prevLi);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
            pagination.appendChild(li);
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(li);
        }
    }
    
    // 下一页按钮
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">
            <i class="fas fa-chevron-right"></i>
            下一页
        </a>
    `;
    pagination.appendChild(nextLi);
}

// 显示加载状态
function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('adminTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'none';
}

// 显示空状态
function showEmptyState() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('adminTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'block';
    updateAdminCount(0);
}


// 更新管理员数量显示
function updateAdminCount(count) {
    document.getElementById('listCount').textContent = count;
}

// 切换页面
function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) return;
    currentPage = page;
    getAdmins(); // 重新加载数据而不是本地分页
}

// 筛选管理员
function filterAdmins() {
    currentPage = 1; // 重置到第一页
    getAdmins(); // 重新加载数据
}

// 重置筛选器
function resetFilters() {
    document.getElementById('searchInput').value = '';
    currentPage = 1;
    getAdmins(); // 重新加载数据
}


// 处理添加管理员
async function addAdmin(event) {
    event.preventDefault();

    const form = event.target;
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        return;
    }

    const formData = new FormData(form);
    const adminData = {
        username: formData.get('username'),
        password: formData.get('password'),
        role: "1",
    };

    try {
        const response = await fetch('/api/admins', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(adminData)
        });

        const result = await response.json();

        if (result.success) {
            // 添加成功
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('addAdminModal')).hide();
            resetAddForm(); // 重置表单
            getAdmins(); // 重新加载
        } else {
            // 添加失败
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('添加管理员出错:', error);
        showError('添加失败：网络错误');
    }
}



// 编辑管理员
function editAdmin(adminId) {
    const admin = allAdmins.find(c => c.id === adminId);
    if (!admin) {
        showError('管理员不存在');
        return;
    }

    currentEditingAdminId = adminId;

    // 填充编辑表单
    document.getElementById('editAdminId').value = admin.id;
    document.getElementById('editAdminUsername').value = admin.username;
    document.getElementById('editAdminPassword').value = admin.password;
    
    new bootstrap.Modal(document.getElementById('editAdminModal')).show();
}


// 处理编辑课程
async function handleEditAdmin(event) {
    event.preventDefault();

    const form = event.target;
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        return;
    }

    const formData = new FormData(form);
    const adminData = {
        id: parseInt(formData.get('id')),
        username: formData.get('username'),
        password: formData.get('password'),
    };

    try {
        const response = await fetch(`/api/admins/${adminData.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(adminData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('editAdminModal')).hide();
            resetEditForm(); // 重置表单
            getAdmins(); 
        } else {
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('更新管理员出错:', error);
        showError('更新失败：网络错误');
    }
}


// 删除
function deleteAdmin(adminId, adminUsername) {
    currentEditingAdminId = adminId;
    document.getElementById('deleteAdminInfo').textContent = adminUsername;
    new bootstrap.Modal(document.getElementById('deleteAdminModal')).show();
}


// 处理删除逻辑
async function handleDeleteAdmin() {
    if (!currentEditingAdminId) return;

    try {
        const response = await fetch(`/api/admins/${currentEditingAdminId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            // 删除成功
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('deleteAdminModal')).hide();
            currentEditingAdminId = null; // 重置当前编辑ID
            getAdmins(); // 重新加载列表
        } else {
            // 删除失败
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('删除管理员出错:', error);
        showError('删除失败：网络错误');
    }
}

// 重置添加表单
function resetAddForm() {
    const form = document.getElementById('addAdminForm');
    form.reset();
    form.classList.remove('was-validated');
}

// 重置编辑表单
function resetEditForm() {
    const form = document.getElementById('editAdminForm');
    form.reset();
    form.classList.remove('was-validated');
    currentEditingAdminId = null;
}